package com.ciwong.epaper.modules.login;

import android.text.TextUtils;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.me.util.MeUtil;
import com.ciwong.epaper.util.EConstants;

/**
 * 登录中间层实现
 * Created by lqi on 2017/2/22.
 */
public class LoginPresenterImpl implements LoginContract.LoginPresenter, LoginFinishedListener {

    private LoginContract.LoginView mLoginView;
    private LoginContract.LoginModel mLoginModel;
    private EApplication mEApplication;

    public LoginPresenterImpl(EApplication application, LoginContract.LoginView loginView) {
        this.mEApplication = application;
        this.mLoginView = loginView;
        mLoginModel = new LoginModelImpl();
    }

    @Override
    public void validateCredentials(String userId, String password, String uuid, String captchaCode) {
        //登陆区分游客模式
        if (EConstants.IS_YOUKE) {
            EConstants.CLIENT_ID = EConstants.YOUKE_CLIENT_ID;
            EConstants.CLIENT_SECRECT = EConstants.YOUKE_CLIENT_SECRECT;
        } else {
            EConstants.CLIENT_ID = EConstants.NOMOR_CLIENT_ID;
            EConstants.CLIENT_SECRECT = EConstants.NOMOR_CLIENT_SECRECT;
        }

        boolean cancel = false;
        boolean isMobile = false;
        if (TextUtils.isEmpty(userId)) {
            cancel = mLoginView.setUerNameError(mEApplication.getApplicationContext().getString(R.string.account_null));
        } else if (!mLoginView.isValidUserName(userId)) {
            cancel = mLoginView.setUerNameError(mEApplication.getApplicationContext().getString(R.string.account_format_wrong));
        } else if (TextUtils.isEmpty(password)) {
            cancel = mLoginView.setPasswordError(mEApplication.getApplicationContext().getString(R.string.password_null));
        }
        if (!cancel) {
            if (MeUtil.isMobileNum(userId)) {
                isMobile = true;
            }
            mLoginView.showLoginProgress(true);
            mLoginModel.login(mEApplication, userId, password, uuid, captchaCode,this,  isMobile);
        }

    }


    @Override
    public void onLoginSuccess(boolean isBindPhone, String pwd) {
        mLoginView.showLoginProgress(false);
        mLoginView.navigateToHome(isBindPhone, pwd);
    }

    @Override
    public void onLoginFiled(Object data) {
        mLoginView.showLoginProgress(false);
        mLoginView.showLoginErrorMsg(mEApplication.getApplicationContext().getString(R.string.connect_disable5));
    }

    @Override
    public void onLoginFiled(int errorCode, String msg) {
        mLoginView.showLoginProgress(false);
        if (errorCode == 26) {
            msg = mEApplication.getApplicationContext().getString(R.string.server_error);
        }
        mLoginView.showLoginErrorMsg(msg);
    }
}
